<html>
<head>
<title>角色管理</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>

<link rel="shortcut icon" href="resources/images/lock.png" type="image/x-icon">
<link rel="stylesheet" href="resources/css/stylemain.css">
<link rel="stylesheet" href="resources/layui/css/layui.css">

<link rel="stylesheet" href="resources/layui/css/treeTable.css">
<link rel="stylesheet" href="resources/font-awesome-4.7.0/css/font-awesome.min.css" media="all">
<script src="resources/layui/layui.all.js"></script>
<script type="text/javascript" src="resources/js/jquery.js"></script>
<script type="text/javascript" src="resources/js/base64.js"></script>
</head>
<body>
<div class="layui-form">
  <table class="layui-hide" id="test" lay-filter="test"></table>
  <div id="page"></div>
  <script type="text/html" id="toolbarDemo">
  <div class="layui-btn-container">
    <button class="layui-btn layui-btn-sm" lay-event="add" style="display:none"><i class="layui-icon layui-icon-add-circle"></i> 新增角色</button>    
    <button class="layui-btn layui-btn-sm" lay-event="edit"><i class="layui-icon layui-icon-edit"></i> 修改角色</button>
	<button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="del" style="display:none"><i class="layui-icon layui-icon-delete"></i> 删除</button>

  </div>
  </script>
</div>

<script id="roleadd" type="text/html">
<div style="width:360px;margin-top:20px">
	<form class="layui-form" action="" id="f_roleadd">
		<div class="layui-form-item">
		    <label class="layui-form-label">角色名称</label>
		    <div class="layui-input-block">
		      <input type="text" id="f_rolename" name="rolename" lay-verify="required" lay-reqtext="名称是必填项，岂能为空？" placeholder="请输入" autocomplete="off" class="layui-input">
		    </div>
		 </div>
		 <div class="layui-form-item">
		  	<label class="layui-form-label">下级可选</label>
		  	<div class="layui-input-block">
		      <input type="checkbox" id="subflags" name="subflags" lay-skin="primary" title="" checked="">
		    </div>
	  	</div>
	  	<div class="layui-form-item">
	    	<label class="layui-form-label">功能权限</label>
		    <div class="layui-input-block">
		      <div id="right_tree" style="height: 350px;overflow: auto;"></div>
		    </div>
	  	</div>	  	
	</form>
</div>
</script>
<script type="text/javascript">
var table = layui.table;
var form = layui.form;
var tree = layui.tree;
var curopt = "";

layui.use([], function(){
	getData();
	
	
	 
});

$('#ckpassword').on('keydown', function (event) {
    if (event.keyCode == 13) {
    	//debugger;
    	userckopt();
		layer.closeAll();
    }
});

function getRightlist(){
	$.ajax({
		contentType: "application/json;charset=UTF-8",
		url : "righttree.do?",
		type : "get",
		dataType : "json",
		success : function(msg) {
			//debugger;
			tree.render({
			    elem: '#right_tree' //默认是点击节点可进行收缩
			    ,data: msg
			    ,id: 'rightlist'
			    ,showLine: false
			    ,showCheckbox: true
			  });
			
		},
	    error : function(e){
	    	//dispalyEasyUILoad();
	        alert(e.status);
	        alert(e.responseText);
	    }
	});
}

function dialog_add(){
	getRightlist();
	var win = layer.open({
		  type: 1 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
		  ,title: "添加角色" //标题
		  ,skin:""   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
		  ,area: ['400px', '620px'] //宽度、高度
		  ,shade: 0.3
		  ,offset: 'auto'
		  ,anim:5 //弹出动画
		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
		  ,content: $("#roleadd").html()     //内容
		  ,btn: ['确定', '取消'] //只是为了演示
		  ,success:function(layero){
			     var mask = $(".layui-layer-shade");
			     mask.appendTo(layero.parent());
			     //其中：layero是弹层的DOM对象
			     //$('#f_rolename').removeAttr("disabled");
			     form.render();
			}
		,yes: function(index, layero){
		    //按钮【按钮一】的回调
		    	//debugger;
		    	if(submitForm('','')){
		    		//$("#roleadd").css('display','none');
				 	layer.close(index);
		    	}
	    	
		  }
		  ,btn2: function(index, layero){
		    //按钮【按钮二】的回调
		    
		    	//$("#roleadd").css('display','none'); 
		    	
		  }
		  ,cancel: function(){ 
			    //右上角关闭回调
			   // $("#roleadd").css('display','none'); 
			    
		 }
	});
}

function ckdialgo_auth(){
	layer.open({
		  type: 1 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
		  ,title: "复核" //标题
		  ,skin:"layui-layer-lan"   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
		  ,area: ['350px', '220px'] //宽度、高度
		  ,shade: 0.3
		  ,offset: 'auto'
		  ,anim:5 //弹出动画
		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
		  ,content: $("#dlgck")     //内容
		  ,btn: ['确定', '取消'] //只是为了演示
		  ,success:function(layero){
			     var mask = $(".layui-layer-shade");
			     mask.appendTo(layero.parent());
			     $('#ckname').focus();
			     //其中：layero是弹层的DOM对象
			}
		 ,yes: function(index, layero){
		    //按钮【按钮一】的回调
		    	userckopt();
	    		$("#dlgck").css('display','none');
			 	layer.close(index);
		    	
			 	 
		  }
		  ,btn2: function(index, layero){
		    //按钮【按钮二】的回调
		    
		    	$("#dlgck").css('display','none'); 
		    	
		  }
		  ,cancel: function(){ 
			    //右上角关闭回调
			    $("#dlgck").css('display','none'); 
			    
		 }
	});
}

function addrights(obj,rights){
	if(rights.length > 0){		
		rights.forEach(function(right){  
			//debugger;
			
			if(right.isleaf == 1){
				obj['children'].push(right.id);				
			}else{
				if(right.children.length > 0){
					addrights(obj,right.children);
				}
			}		    
		});
	}
}

function submitForm(ckname,ckpassword){
	/*if(/^[\Α-\￥]+$/i.test($('#username').textbox('getValue')) == true){
		$.messager.alert('通知',"用户名不能有中文!",'info');
		return;
	}*/
	if($('#f_rolename').val().replace(/\s+/g,"").length < 2 || $('#f_rolename').val().replace(/\s+/g,"").length > 8){
		layer.open({
	        title: "通知"
	        ,content: '角色名称为2~8位!'	        
	      });
		return false;
	}
	
	//debugger;
	var datastring = '';
	if(curopt == "add"){
		datastring = '{"rolename":"'+$("#f_rolename").val() + '","subflags":' 
		+ ($('#subflags').prop('checked')?1:0) + ',"roleid":"","ckname":"'+ckname+'","ckpassword":"'+ckpassword+'","rname":"系统管理/角色管理/新增修改","children":[]}';
	}else if(curopt == "edit"){
		var checkStatus = table.checkStatus('test');
		datastring = '{"rolename":"'+$("#f_rolename").val() + '","subflags":' 
		+ ($('#subflags').prop('checked')?1:0) + ',"roleid":"' + checkStatus.data[0].roleid  + '","ckname":"'+ckname+'","ckpassword":"'+ckpassword+ '","rname":"系统管理/角色管理/新增修改","children":[]}';
	}
	
	var obj = JSON.parse(datastring);
	var rights = tree.getChecked('rightlist');

	if(rights.length > 0){		
		rights.forEach(function(right){  
			//debugger;
			
			if(right.isleaf == 1){
				obj['children'].push(right.id);				
			}else{
				if(right.children.length > 0){
					addrights(obj,right.children);
				}
			}		    
		});
	}
	//debugger;
	
	datastring = JSON.stringify(obj);
	$.ajax({
		type:"post",
		contentType: "application/json;charset=UTF-8",
		url: "roleaddupdate.do?",
		async:false,
		data:datastring,
     	dataType:"json",
        success: function(msg) {    //数据提交成功时返回数据
        	if(msg.status == "1"){
        		getData();
        		layer.closeAll();
        		return true;
        	}else if(msg.status == "1211"){
        		$('#ckname').val('');
				$('#ckpassword').val('');
				ckdialgo_auth();
				return true;
			}else{
        		layer.msg(msg.desc);
        		return false
        	}
        							
			
        },
        error : function(e){
            alert(e.status);
            alert(e.responseText);
        }

	});
	return false;
}

table.on('toolbar(test)', function(obj){
	//debugger;
	var checkStatus = table.checkStatus(obj.config.id);
    switch(obj.event){
      case 'add':
    	  curopt = 'add';
    	  dialog_add();
      break;
      case 'del':
    	//debugger;
    	curopt = "del";
    	if(checkStatus.data.length == 0){
    		layer.msg('请先选择角色!');
    		return;
    	}
        u_remove('','');
      break;
      case 'edit':
    	  if(checkStatus.data.length == 0){
      		layer.msg('请先选择角色!');
      		return;
      	  }
    	  curopt = 'edit';
    	  dialog_edit('','',checkStatus.data[0]);
      break;      
    };
  });

function getData(){
	table.render({
		  elem: '#test'
		  ,toolbar: '#toolbarDemo'
		  ,url:'getRoleList'
		  ,cellMinWidth: 50 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
		  ,cols: [[
			  {type:'radio', hide: true}
			  ,{field:'rolename', title: '角色名'} //width 支持：数字、百分比和不填写。你还可以通过 minWidth 参数局部定义当前单元格的最小宽度，layui 2.2.1 新增
			    ,{field:'subflags', title: '下级可选', align: 'center', templet: '#statusTpl'}
			    ,{field:'orgname', title: '所属部门'}
			    ,{field:'createtime', title: '创建时间'}
			    ,{field:'updatetime', title: '最后更新'}
		  ]]
		  ,page:true
		  ,limit:20
		  ,height: parent.iframeH - 60
		});	
	
	table.on('row(test)', function(obj){
	    var data = obj.data;    
	    obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
		//选中radio样式
		obj.tr.find('i[class="layui-anim layui-icon"]').trigger("click");
	});
}


function dialog_edit(ckname,ckpassword,data){	
	var win = layer.open({
		  type: 1 //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层） 
		  ,title: "编辑角色" //标题
		  ,skin:""   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
		  ,area: ['400px', '620px'] //宽度、高度
		  ,shade: 0.3
		  ,offset: 'auto'
		  ,anim:5 //弹出动画
		  ,shadeClose: false //弹框出现后，允许点击其它地方关闭
		  ,content: $("#roleadd").html()     //内容
		  ,btn: ['确定', '取消'] //只是为了演示
		  ,success:function(layero){
			     //var mask = $(".layui-layer-shade");
			     //mask.appendTo(layero.parent());
			     //其中：layero是弹层的DOM对象
			  	$('#f_rolename').val(data.rolename);
			     //debugger;
				if(data.subflags == '1'){
					$("#subflags").prop("checked",true);
				}else{
					$("#subflags").prop("checked",false);
					
				}	
			     //$('#f_rolename').attr("disabled","disabled");
			     $.ajax({
			 		contentType: "application/json;charset=UTF-8",
			 		url : "righttree.do?",
			 		type : "get",
			 		dataType : "json",
			 		success : function(msg) {
			 			tree.render({
			 			    elem: '#right_tree' //默认是点击节点可进行收缩
			 			    ,data: msg
			 			    ,id: 'rightlist'
			 			    ,showLine: false
			 			    ,showCheckbox: true
			 			});
			 			findrolerights(data);
			 		},
			 	    error : function(e){
			 	    	if(e.status == 200){
			        		parent.location.href = "login";
			        	}else{
			        		alert(e.status);
			                alert(e.responseText);
			        	}
			 	    }
			 	});
			     
			     
			     form.render();
			}
		,yes: function(index, layero){
		    //按钮【按钮一】的回调		    	
		    	if(submitForm('','')){
		    		//$("#roleadd").css('display','none');
				 	layer.close(index);
		    	}
	    		
		  }
		  ,btn2: function(index, layero){
		    //按钮【按钮二】的回调
		    
		    	//$("#roleadd").css('display','none'); 
		    	
		  }
		  ,cancel: function(){ 
			    //右上角关闭回调
			   // $("#roleadd").css('display','none'); 
			    
		 }
	});
}

function findrolerights(data){
	var datastring = '{"roleid":"'+data.roleid+'"}';
	//debugger;
	$.ajax({
		type:"post",
		contentType: "application/json;charset=UTF-8",
		url: "getRoleRights.do?",
		async:false,
		data:datastring,
     	dataType:"json",
        success: function(msg) {    //数据提交成功时返回数据
        	//debugger;
			if(msg.status == "1"){
				var jnode = msg.children;
				for(i=0; i<jnode.length;i++){
					tree.setChecked('rightlist', [jnode[i].rightid]);
				}
			}else{
				layer.msg(msg.desc);
			}		        			
			
        },
        error : function(e){
        	if(e.status == 200){
        		parent.location.href = "login";
        	}else{
        		alert(e.status);
                alert(e.responseText);
        	}
        }

	});
}

 
function u_remove(ckname,ckpassword){	
	var userdata = table.checkStatus('test');
	var row = userdata.data[0];
	if (row){
		//debugger;
		var datastring = '{"roleid":"'+row.roleid+'","rname":"系统管理/角色管理/删除","rolename":"' + row.rolename + '","role_org":'+row.org_id+ ',"ckname":"' + ckname + '","ckpassword":"' + ckpassword + '"}';
		layer.confirm('确定要删除该角色?', {
			  btn: ['取消', '确定'] //可以无限个按钮				  
			}, function(index, layero){
			  //按钮【按钮一】的回调
				layer.closeAll();
			}, function(index){
				$.ajax({
					type:"post",
					contentType: "application/json;charset=UTF-8",
					url: "roledel.do?",
					async:false,
					data:datastring,
			     	dataType:"json",
			        success: function(msg) {    //数据提交成功时返回数据
						if(msg.status == "1"){
							layer.closeAll();
							getData();									
						}else if(msg.status == "1211"){
							$('#ckname').val('');
							$('#ckpassword').val('');							
							ckdialgo_auth();
			        		
						}else{
							layer.msg(msg.desc);
						}						
						
			        },
			        error : function(e){
			        	if(e.status == 200){
			        		parent.location.href = "login";
			        	}else{
			        		alert(e.status);
			                alert(e.responseText);
			        	}
			        }

			});	
		});
							
	}else{
		layer.msg('需选择用户!');
	}							
}

function userckopt(){
	//debugger;
	var ckname = $('#ckname').val();
	if(ckname == ''){
		layer.msg('请填写用户账号!');
		return;
	}
	var ckpassword = $('#ckpassword').val();
	if(curopt == "add"){
		submitForm(ckname,$.base64.encode(ckpassword));
	}else if(curopt == "edit"){
		submitForm(ckname,$.base64.encode(ckpassword));
	}else if(curopt == "del"){
		u_remove(ckname,$.base64.encode(ckpassword));
	}
	
	
}

function userckopt_cancel(){
	$('#ckname').val('');
	$('#ckpassword').val('');	
}
</script>
<script type="text/html" id="statusTpl">
  {{#  if(d.subflags == '0'){ }}	
    <span style="color: #F581B1;">否</span>
  {{#  } else if(d.subflags == '1') { }}
    <span style="color: #F581B1;">是</span>
  {{#  } }}
</script>

</body>
</html>
